﻿using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Versioning;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.Helpers.Converter;
using Rio.Framework.Pages.Extensions;
using Telerik.Windows.Controls;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
using System;

namespace Rio.Framework.Pages.ChildWindows
{
    public partial class AddDocumentVersionChildWindow : RadWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private FileInfo _selectedFile;
        private VersioningItem _selectedVersion;
        private bool _useSelectedFile;

        #region Properties

        public FileInfo SelectedFile
        {
            get { return _selectedFile; }
            set
            {
                _selectedFile = value;
                OnPropertyChanged("SelectedFile");
                ValidWindow.RaiseCanExecuteChanged();
            }
        }
        public bool UseSelectedFile
        {
            get { return _useSelectedFile; }
            set
            {
                _useSelectedFile = value;
                OnPropertyChanged("UseSelectedFile");
                ValidWindow.RaiseCanExecuteChanged();
            }
        }
        public VersioningItem SelectedVersion
        {
            get { return _selectedVersion; }
            set
            {
                _selectedVersion = value;
                OnPropertyChanged("SelectedVersion");
                ValidWindow.RaiseCanExecuteChanged();
            }
        }
        public ObservableCollection<VersioningItem> Versions { get; set; }
        public VersionType CurrentVersionType { get; set; }
        public bool IsMajor { get; set; }
        public MajorMinorToBooleanConverter MajorMinorToBooleanConverter
        {
            get
            {
                return (this.Resources["MajorMinorToBooleanConverter"] as MajorMinorToBooleanConverter);
            }
        }
        public Document CurrentDocument { get; set; }

        private bool maxMajorReached { get; set; }
        private bool maxMinorReached { get; set; }

        public RelayCommand ValidWindow { get; set; }

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="AddDocumentVersionChildWindow"/> class.
        /// </summary>
        public AddDocumentVersionChildWindow(Document document)
        {
            InitializeComponent();

            InitLabels();

            ValidWindow = new RelayCommand(CloseWindow, CanExecute);

            CurrentDocument = document;
            UseSelectedFile = true;
            
            ManageAccessibility();

            this.CanMove = false;
            this.ResizeMode = Telerik.Windows.Controls.ResizeMode.NoResize;
            this.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterScreen;
        }

        /// <summary>
        /// Inits the labels.
        /// </summary>
        private void InitLabels()
        {

            this.Header = Resx.GetLabel(ResxFolderPage.ADD_A_NEW_VERSION);
            VersionType.Text = Resx.GetLabel(ResxFolderPage.VERSION_TYPE);
            MajorRadioButton.Content = Resx.GetLabel(ResxFolderPage.MAJOR);
            MinorRadioButton.Content = Resx.GetLabel(ResxFolderPage.MINOR);
            FileTextBlock.Text = Resx.GetLabel(ResxFolderPage.SOURCE);
            BrowseButton.Content = Resx.GetLabel(ResxFolderPage.BROWSE);
            OKButton.Content = Resx.GetLabel(ResxCommon.OK);
            CancelButton.Content = Resx.GetLabel(ResxCommon.CANCEL);
            FilesSystemTextBlock.Content = Resx.GetLabel(ResxFolderPage.FILE_SYSTEM);
            OldVersionTextBlock.Content = Resx.GetLabel(ResxFolderPage.OLD_VERSION);
        }

        /// <summary>
        /// Handles the Click event of the CancelButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        /// <summary>
        /// Closes the window.
        /// </summary>
        private void CloseWindow()
        {
            this.DialogResult = true;
            this.Close();
        }

        /// <summary>
        /// Determines whether this instance can execute.
        /// </summary>
        /// <returns>
        ///   <c>true</c> if this instance can execute; otherwise, <c>false</c>.
        /// </returns>
        private bool CanExecute()
        {
            if (CurrentDocument.CurrentModelVersion.ModelType == NetBay.Core.BusinessEntities.Versioning.VersionType.NoControl)
            {
                if (SelectedFile == null)
                    return false;
                else
                    return true;
            }
            else
            {
                if (UseSelectedFile)
                {
                    if (SelectedFile == null)
                        return false;
                    else
                        return true;
                }
                else
                {
                    if (SelectedVersion == null)
                        return false;
                    else
                        return true;
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the Button control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            string filter = Path.GetExtension(this.CurrentDocument.ImageName);
            openFileDialog.Filter = string.Format("(*{0})|*{0}", filter);
            
            if (openFileDialog.ShowDialog() == true)
            {
                if (Path.GetExtension(openFileDialog.File.Name).ToLowerInvariant() == filter.ToLowerInvariant())
                {
                    SelectedFile = openFileDialog.File;
                    selectedFilenameTextBlock.Text = SelectedFile.Name;
                }
                else
                {
                    MessageBoxChildWindow errorMessage = new MessageBoxChildWindow(String.Empty, "Le type du fichier sélectionné n'est pas le même que celui de l'actuelle version.", MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    errorMessage.Show();
                }
            }
        }

        /// <summary>
        /// Handles the KeyUp event of the childWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
        private void childWindow_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.DialogResult = false;
            }
        }

        /// <summary>
        /// Handles the Loaded event of the childWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void childWindow_Loaded(object sender, RoutedEventArgs e)
        {
            IsMajor = (bool)MajorMinorToBooleanConverter.Convert(CurrentDocument, typeof(bool), "Major", null);
        }

        /// <summary>
        /// Manage accessibility buttons
        /// </summary>
        /// <returns></returns>
        private void ManageAccessibility()
        {
            switch (CurrentDocument.CurrentModelVersion.ModelType)
            {
                case NetBay.Core.BusinessEntities.Versioning.VersionType.NoControl:
                    this.MajorRadioButton.IsEnabled = false;
                    this.MinorRadioButton.IsEnabled = false;
                    this.OldVersionsContentControl.IsEnabled = false;
                    break;

                case NetBay.Core.BusinessEntities.Versioning.VersionType.Major:
                    this.MajorRadioButton.IsEnabled = true;
                    this.MinorRadioButton.IsEnabled = false;
                    this.OldVersionsContentControl.IsEnabled = true;
                    break;

                case NetBay.Core.BusinessEntities.Versioning.VersionType.MajorMinor:
                    this.MajorRadioButton.IsEnabled = true;
                    this.MinorRadioButton.IsEnabled = true;
                    this.OldVersionsContentControl.IsEnabled = true;
                    break;
            }
        }

        /// <summary>
        /// Called when [property changed].
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}